<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据存储</title>
</head>

<body>
    <button class="btn">创建成绩</button>
    <button class="clear">清除</button>
    <h3>排行榜</h3>
    <ol class="rank"></ol>
    <script>
        let btn = document.querySelector('.btn');
        let rankEle = document.querySelector('.rank');
        let clear = document.querySelector('.clear');
        let rank;
        if (localStorage.rank) {
            rank = JSON.parse(localStorage.rank);
        } else {
            localStorage.rank = JSON.stringify([]);
            rank = JSON.parse(localStorage.rank);
        }
        let str = "";
        rank.forEach(v => {
            str += `<li>${v}</li>`
        });
        rankEle.innerHTML = str;
        btn.onclick = () => {
            let r = Math.floor(Math.random() * 100);
            rank.push(r);
            alert(r);
            rank.sort((a, b) => {
                if (a < b) {
                    return 1;
                } else {
                    return -1;
                }
            })
            rank=rank.slice(0,10);
            localStorage.rank=JSON.stringify(rank);
            if (localStorage.rank) {
                rank = JSON.parse(localStorage.rank);
            } else {
                localStorage.rank = JSON.stringify([]);
                rank = JSON.parse(localStorage.rank);
            }
            let str = "";
            rank.forEach(v => {
                str += `<li>${v}</li>`
            });
            rankEle.innerHTML = str;
        }
        clear.onclick = () => {
            localStorage.removeItem("rank");
            // localStorage.clear();
        }  
    </script>
</body>

</html>